import requests
import json

if __name__ == '__main__':
    url = "https://spark-api-open.xf-yun.com/v2/chat/completions"
    data = {
        "max_tokens": 3890,
        "top_k": 4,
        "temperature": 1.2,
        "messages": [
            { 
                "role": "system",
                "content": "需基于用户输入的舞蹈相关需求（如 \"芭蕾风格的手臂伸展动作\"\"街舞的腿部弹跳动作\"\"头部左右摆动 3 秒\"），生成包含5 个肢体动作参数 + 1 个时间参数的结构化 JSON 指令，确保指令可直接被舞蹈动作解析系统识别，无格式错误、无参数无效、无字段缺失问题。{\n  \"left_arm\": 90,\n  \"right_arm\": -45.5,\n  \"left_leg\": 30,\n  \"right_leg\": 0,\n  \"head\": 15,\n  \"duration\": 2.3\n}说明：左臂水平上举 90°、右臂向后摆 45.5°、左腿微屈 30°、右腿伸直（0°）、头部向右摆 15°，整套动作持续 2.3 秒，参数符合物理极限，语法无错误。"
            },
            {
                "role": "user",
                "content": "给出摇滚的舞蹈动作"
            }
        ],
        "model": "x1",
        "tools": [
            {
                "web_search": {
                    "search_mode": "normal",
                    "enable": False
                },
                "type": "web_search"
            }
        ]
    }
    data["stream"] = True
    header = {
        "Authorization": "Bearer AigHMUBVsFiSZsVzMdfP:RaJRsEtuUeNnevWnbPZW"
    }
    
    try:
        response = requests.post(url, headers=header, json=data, stream=True)
        response.encoding = "utf-8"
        
        # 处理流式响应
        for line in response.iter_lines(decode_unicode=True):
            if line:
                # 移除"data:"前缀并解析JSON
                if line.startswith("data:"):
                    json_str = line[5:]  # 移除"data:"前缀
                    if json_str.strip() == "[DONE]":
                        break
                    try:
                        json_data = json.loads(json_str)
                        if "choices" in json_data and len(json_data["choices"]) > 0:
                            content = json_data["choices"][0].get("delta", {}).get("content", "")
                            if content:
                                print(content, end="", flush=True)
                    except json.JSONDecodeError:
                        print(f"无法解析JSON: {json_str}")
                else:
                    print(line)
    except requests.RequestException as e:
        print(f"请求出错: {e}")